import { login, getInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  roles: [],
  user_name: '',
  password: '',
  todoNews: 99
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERNAME: (state, user_name) => {
    state.user_name = user_name
  },
  SET_PASWORD: (state, password) => {
    state.password = password
  },
  SET_TODONEWS: (state, todoNews) => {
    state.todoNews = todoNews
  }
}

const actions = {
  // user login
  login({ commit }, token) {
    return new Promise((resolve, reject) => {

      
      commit('SET_TOKEN', token)
      setToken(token)
      sessionStorage.setItem('token', token)
      resolve()
    })
  },
  // get user info
  // roles 类别
  // * admin: 开发者
  // * 127: 多媒体_普通用户
  // * 128: 多媒体_素材审核管理员
  // * 129: 多媒体_终端发布管理员
  // * -1(terminal):  终端登录
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then((response) => {
  //       // response.data.todoNews = 99
  //       const { data } = response
  //       if (!data) {
  //         reject('验证失败，请重新登录!')
  //       }
  //       const { roleIdList, displayName, username, password, todoNews } = data
  //       // 角色必须是非空数组
  //       if (!roleIdList || roleIdList.length <= 0) {
  //         reject('获取信息: 角色必须是非空数组!')
  //       }
  //       commit('SET_ROLES', roleIdList)
  //       commit('SET_NAME', displayName)
  //       commit('SET_USERNAME', username)
  //       commit('SET_PASWORD', password)
  //       // commit('SET_TODONEWS', todoNews)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // }
  getInfo(context, token){
    return new Promise((resolve,reject)=>{
      getInfo(token).then((response) => {
        
        const { data } = response
        if(data.code != 200){
          reject()
        }
        resolve(data)
      })
    }).catch(res => res)

  },


  // user logout
  logout({ commit, state }) {
    commit('SET_TOKEN', '')
    removeToken()
    resetRouter()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

